<template>
  <div class="main">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchMap" class="demo-form-inline showtable" ref="searchMap">
      <el-form-item prop="username">
        <el-input v-model="searchMap.username" placeholder="用户名" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="$refs['searchMap'].resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格显示 -->
    <el-table :data="tableData" style="width: 100%" max-height="460px" border stripe>
      <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" width="160" align="center"></el-table-column>
      <el-table-column prop="address" label="收货地址" align="center"></el-table-column>
      <el-table-column prop="phonenum" label="手机号" width="160" align="center"></el-table-column>
      <el-table-column prop="gid" label="商品" width="200" align="center" v-if="goodsArr.length!=0">
        <template slot-scope="scope">
          <span>{{scope.row.gid | goodsFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="gcount" label="数量" width="120" align="center"></el-table-column>
      <el-table-column prop="color" label="颜色" width="120" align="center"></el-table-column>
      <el-table-column prop="size" label="码数" width="100" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页显示 -->
    <div class="fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        hide-on-single-page
      ></el-pagination>
    </div>

    <!-- 对话框 -->
    <el-dialog title="编辑订单" :visible.sync="dialogFormVisible" width="500px" top="10px">
      <el-form
        :model="pojo"
        ref="pojoFrom"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        status-icon
        :rules="rules"
      >
        <el-form-item prop="gcount" label="数量：">
          <el-input v-model="pojo.gcount" placeholder="数量"></el-input>
        </el-form-item>
        <el-form-item prop="color" label="颜色：">
          <el-input v-model="pojo.color" placeholder="颜色"></el-input>
        </el-form-item>
        <el-form-item prop="size" label="码数：">
          <el-input v-model="pojo.size" placeholder="码数"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updataOrder('pojoFrom')">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from "@/api/order";
import store from "@/store";
let goodsArr = [];
export default {
  data() {
    return {
      tableData: [],
      currentPage: 1, //当前页
      pageSize: 10, //一页10条数据
      total: 100,
      searchMap: {
        //查询条件
        username: ""
      },
      oldDate: 0, //存旧时间
      newDate: 0, //当前时间(毫秒)
      pojo: {
        //新增会员数据
        gcount: "",
        color: "",
        size: "",
        id: ""
      },
      goodsArr,
      dialogFormVisible: false, //对话框的显示
      rules: {
        //新增会员验证
        gcount: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        color: [{ required: true, message: "请输入商品颜色", trigger: "blur" }],
        size: [{ required: true, message: "请输入商品码数", trigger: "blur" }]
      }
    };
  },

  components: {},

  methods: {
    //获取分页数据
    async getOrder() {
      try {
        //把要第几页、一页多少条一并发给后端
        let p = await orderApi.searchorder(this.currentPage, this.pageSize);
        // console.log(p);
        if (p.data.flag) {
          if (p.data.data.length > this.pageSize) {
            let arr = [];
            for (let i = 0; i < this.pageSize; i++) {
              arr.push(p.data.data[i]);
            }
            this.tableData = arr;
          } else {
            this.tableData = p.data.data;
          }
          this.total = p.data.totalcount;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //点击查询
    onSubmit() {
      let istrue = this.clickToFast();
      if (istrue) {
        this.getSearch(this.searchMap);
        // console.log("过了800毫秒了");
      } else {
        console.log("还没过800毫秒");
      }
    },
    //搜索订单
    async getSearch(searchMap) {
      try {
        let p = await orderApi.getOrder(searchMap);
        if (p.data.flag) {
          this.tableData = p.data.data;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //更换一页条数
    handleSizeChange(val) {
      //val  是当页面条数发生改变时 传入得新值  如  当页面初始条数是10 点击更换成20条 那val就是20
      this.pageSize = val;
      this.getSearch();
    },
    //更换当前页码
    handleCurrentChange(val) {
      //val 当点击更换当前页时  val就是要更换得页码数
      this.currentPage = val;
      this.getSearch();
    },
    //删除订单
    handleDelete(row) {
      this.$confirm("确定要删除该订单吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteUser(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //删除订单，请求ajax
    async deleteUser(row) {
      try {
        let p = await orderApi.delorder(row);
        if (p.data.flag) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getOrder();
        } else {
          this.$message({
            type: "erroe",
            message: "删除失败!"
          });
        }
      } catch (err) {
        console.log("ajax请求失败", err);
      }
    },
    //防止点击过快
    clickToFast() {
      this.oldDate = this.newDate;
      this.newDate = new Date().getTime();
      if (this.newDate - this.oldDate > 800) {
        return true;
      } else {
        return false;
      }
    },
    //修改信息弹窗
    handleEdit(row) {
      this.dialogFormVisible = true;
      // console.log(row.id);
      this.pojo.id = row.id;
      for (let key in this.pojo) {
        this.pojo[key] = row[key];
      }
    },
    //更新订单
    updataOrder(pojoFrom) {
      this.$refs[pojoFrom].validate(vaild => {
        if (vaild) {
          this.updataUser(this.pojo);
        } else {
          this.$message({
            message: "亲，您还没填完噢",
            type: "error"
          });
        }
      });
    },
    //请求ajax 更新订单
    async updataUser(pojo) {
      // console.log(pojo);
      try {
        let p = await orderApi.updataorder(pojo);
        if (p.data.flag) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.dialogFormVisible = false;
          this.tableData.forEach(item => {
            if (item.id == pojo.id) {
              for (let key in pojo) {
                item[key] = pojo[key];
              }
            }
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      } catch (err) {
        console.log("ajax请求出错", err);
      }
    },
    //获取所有商品
    async getgoods() {
      try {
        let p = await orderApi.getgoods();
        if (p.data.flag) {
          localStorage.setItem("goodsFilter", JSON.stringify(p.data.data));
        } else {
          console.log(err);
        }
      } catch (err) {
        console.log(err);
      }
    }
  },
  created() {
    this.getOrder();
    this.getgoods();
    goodsArr = JSON.parse(localStorage.getItem("goodsFilter"));
  },
  //过滤器
  filters: {
    goodsFilter(type) {
      // console.log(type);
      // console.log(type);

      return goodsArr.filter(item => item.gid == type)[0].gname;
    }
  }
};
</script>

<style scoped lang="scss">
.main {
  height: 80%;
}
</style>